package com.sds.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import com.sds.exception.MyException;

public abstract class AbstractReader {
	private static final Map<Class<? extends AbstractReader>, AbstractReader> instanceMap
		= new HashMap<Class<? extends AbstractReader>, AbstractReader>();
	
	private String fileName; 
	private File file;
	private boolean opened = false;
	private FileInputStream fis;
	
	AbstractReader() {}
	
	public static<T extends AbstractReader> T getInstance(Class<T> cls, String fileName) throws MyException {
		AbstractReader ret = instanceMap.get(cls);
		try {
			if (ret == null) {
				synchronized (instanceMap) {
					if (instanceMap.get(cls) == null) {
						instanceMap.put(cls, cls.newInstance());
					}
				}
				ret = instanceMap.get(cls);
			}
			
			ret.fileName = fileName;
			ret.file = new File(fileName);
			ret.openFile();
		} catch (Exception e) {
			throw new MyException();
		}
		
		return (T) ret;
	}
	
	public boolean isOpened() {return opened;}
	private void setOpened(boolean flag) {this.opened = flag;}
	
	public String getFileName() {return fileName;}
	
	protected FileInputStream getFileInputStream() {return fis;}
			
	public void openFile() {
		if (!isOpened()) {
			try {
				fis = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			setOpened(true);
		}
	}
	
}
